package xp2p.inter.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * The Class Server.
 */
public class Server implements Runnable
{
	private int _port;
	private boolean _failure = false;
	private Object _sync;
	private HandlerFactory factory;

	public Server(int port, HandlerFactory factory)
	{
		_port = port;
		_sync = new Object();
		this.factory = factory;
	}

	public void setPort(int port)
	{
		_port = port;
	}

	private Thread thread = null;
	private ServerSocket listener = null;

	public void start()
	{

		thread = new Thread(this);
		thread.start();
	}

	public void stop()
	{
		thread.interrupt();
		try
		{
			listener.close();
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void run()
	{
		try
		{
			listener = new ServerSocket();
			listener.setReuseAddress(true);
			listener.bind(new InetSocketAddress(_port));
		} catch (IOException e1)
		{
			synchronized (_sync)
			{
				_failure = true;
			}
			e1.printStackTrace();
			return;
		}
		while (true)
		{
			Socket client;
			try
			{
				if (listener.isClosed())
				{
					return;
				}
				client = listener.accept();
				ClientHandler handler = new ClientHandler(client, factory);
				Thread handlerThread = new Thread(handler);
				handlerThread.start();
			} catch (IOException e)
			{
				synchronized (_sync)
				{
					_failure = true;
				}
				try
				{
					if (!listener.isClosed())
					{
						listener.close();
					}

				} catch (IOException e1)
				{
					e1.printStackTrace();
					return;
				}
			}
		}
	}

	public boolean wasFailure()
	{
		boolean result;
		synchronized (_sync)
		{
			result = _failure;
		}
		return result;
	}
}
